﻿using System;


using LinFu.AOP.Interfaces;

namespace BrainTechLLC
{
	public class PropChangedTrackerWrapper : AroundMethodBase, IAroundInvoke
	{
		protected override void Execute(IInvocationContext context, CutpointType when, object returnValue)
		{
			if (when != CutpointType.Before || !context.TargetMethod.Name.Contains("set_"))
				return;

			object thisObject = context.Target;			
			string propInfoName = context.TargetMethod.Name.Substring(4);
			Type t = thisObject.GetType();
			PropInfo propInfo = t.GetPropInfo(propInfoName);
			RecordPropertyChangeAttribute[] attrs = propInfo.GetAttributes<RecordPropertyChangeAttribute>();			

			if (attrs != null && attrs.Length > 0)
			{
				object oldValue = propInfo.GetValue(thisObject);
				object newValue = context.Arguments[0];

				for (int n = 0; n < attrs.Length; n++)
				{
					RecordPropertyChangeAttribute attr = attrs[n];
					IPropertyChangeTracker tracker = attr.GetChangeTracker(context.Target, t);

					if (tracker != null)				
						tracker.RecordPropChanged(propInfo.PropertyInfo, oldValue, newValue, context);					
				}
			}
		}
	}
}

